using System;

namespace M13.Utility
{
    /// <summary>
    /// �Ľ���C#LZFѹ������һ���ǳ�С������ѹ���⡣ѹ���㷨�ǳ��졣
    /// <summary>
    public static class Clzf2
    {
        private static readonly uint Hlog = 14;
        private static readonly uint Hsize = (1 << 14);
        private static readonly uint MaxLit = (1 << 5);
        private static readonly uint MaxOff = (1 << 13);
        private static readonly uint MaxRef = ((1 << 8) + (1 << 3));

        /// <summary>
        /// Hashtable
        /// </summary>
        private static long[] _hashTable = null;

        // �����ͷ���ʱ�ڴ�
        public static void Reset()
        {
            _hashTable = null;
        }

        // ѹ�������ֽ�
        public static byte[] Compress(byte[] inputBytes)
        {
            if (inputBytes == null)
            {
                return null;
            }

            if (inputBytes.Length <= 1)
            {
                byte[] copyBytes = new byte[inputBytes.Length];
                Buffer.BlockCopy(inputBytes, 0, copyBytes, 0, inputBytes.Length);
                return copyBytes;
            }

            // ��ʼ�²⣬�����Ҫ���Ժ�����
            int outputByteCountGuess = inputBytes.Length * 2;
            byte[] tempBuffer = new byte[outputByteCountGuess];
            int byteCount = lzf_compress(inputBytes, ref tempBuffer);

            // ����ֽڼ���Ϊ0�������ӻ�����������
            while (byteCount == 0)
            {
                outputByteCountGuess *= 2;
                tempBuffer = new byte[outputByteCountGuess];
                byteCount = lzf_compress(inputBytes, ref tempBuffer);
            }

            byte[] outputBytes = new byte[byteCount];
            Buffer.BlockCopy(tempBuffer, 0, outputBytes, 0, byteCount);
            return outputBytes;
        }

        // ��ѹ��outputBytes
        public static byte[] Decompress(byte[] inputBytes)
        {
            if (inputBytes == null)
            {
                return null;
            }

            if (inputBytes.Length <= 1)
            {
                byte[] copyBytes = new byte[inputBytes.Length];
                Buffer.BlockCopy(inputBytes, 0, copyBytes, 0, inputBytes.Length);
                return copyBytes;
            }

            // ��ʼ�²⣬�����Ҫ���Ժ�����
            int outputByteCountGuess = inputBytes.Length * 3;
            byte[] tempBuffer = new byte[outputByteCountGuess];
            int byteCount = lzf_decompress(inputBytes, ref tempBuffer);

            // ����ֽڼ���Ϊ0�������ӻ�����������
            while (byteCount == 0)
            {
                outputByteCountGuess *= 2;
                tempBuffer = new byte[outputByteCountGuess];
                byteCount = lzf_decompress(inputBytes, ref tempBuffer);
            }

            byte[] outputBytes = new byte[byteCount];
            Buffer.BlockCopy(tempBuffer, 0, outputBytes, 0, byteCount);
            return outputBytes;
        }

        public static void Decompress(byte[] inputBytes, ref byte[] outputBytes)
        {
            if (inputBytes == null)
            {
                return;
            }

            if (inputBytes.Length <= 1)
            {
                outputBytes = inputBytes;
            }

            // ��ʼ�²⣬�����Ҫ���Ժ�����
            int outputByteCountGuess = inputBytes.Length * 3;
            byte[] tempBuffer = new byte[outputByteCountGuess];
            int byteCount = lzf_decompress(inputBytes, ref tempBuffer);

            // ����ֽڼ���Ϊ0�������ӻ�����������
            while (byteCount == 0)
            {
                outputByteCountGuess *= 2;
                tempBuffer = new byte[outputByteCountGuess];
                byteCount = lzf_decompress(inputBytes, ref tempBuffer);
            }

            Buffer.BlockCopy(tempBuffer, 0, outputBytes, 0, byteCount);
        }

        // ע�⣬Ӧ��ʹcompressBuffer�㹻��
        public static byte[] Compress(byte[] inputBytes, byte[] compressBuffer)
        {
            var byteCount = lzf_compress(inputBytes, ref compressBuffer);
            if (byteCount > 0)
            {
                byte[] outputBytes = new byte[byteCount];
                Buffer.BlockCopy(compressBuffer, 0, outputBytes, 0, byteCount);
                return outputBytes;
            }

            return null;
        }

        // ע�⣬Ӧ��ʹcompressBuffer�㹻��
        public static byte[] Decompress(byte[] inputBytes, byte[] decompressBuffer)
        {
            var byteCount = lzf_decompress(inputBytes, ref decompressBuffer);
            if (byteCount > 0)
            {
                byte[] outputBytes = new byte[byteCount];
                Buffer.BlockCopy(decompressBuffer, 0, outputBytes, 0, byteCount);
                return outputBytes;
            }

            return null;
        }

        /// <summary>
        /// ʹ��LibLZF�㷨ѹ������
        /// </summary>
        /// <param name="input">����Ҫѹ��������</param>
        /// <param name="output">�԰���ѹ�����ݵĻ�����������</param>
        /// <returns>�����������ѹ���浵�Ĵ�С</returns>
        static int lzf_compress(byte[] input, ref byte[] output)
        {
            if (input == null || output == null)
            {
                return 0;
            }

            int inputLength = input.Length;
            int outputLength = output.Length;

            // corner case handling
            if (inputLength <= 1)
            {
                if (outputLength >= inputLength)
                {
                    for (int i = 0; i < inputLength; ++i)
                    {
                        output[i] = input[i];
                    }

                    return inputLength;
                }

                return 0;
            }

            // handle HashTable
            if (_hashTable == null)
            {
                _hashTable = new long[Hsize];
            }
            else
            {
                Array.Clear(_hashTable, 0, (int)Hsize);
            }

            long hslot;
            uint iidx = 0;
            uint oidx = 0;
            long reference;

            uint hval = (uint)(((input[iidx]) << 8) | input[iidx + 1]); // FRST(in_data, iidx);
            long off;
            int lit = 0;

            while (true)
            {
                if (iidx < inputLength - 2)
                {
                    hval = (hval << 8) | input[iidx + 2];
                    hslot = ((hval ^ (hval << 5)) >> (int)(((3 * 8 - Hlog)) - hval * 5) & (Hsize - 1));
                    reference = _hashTable[hslot];
                    _hashTable[hslot] = (long)iidx;

                    if ((off = iidx - reference - 1) < MaxOff
                        && iidx + 4 < inputLength
                        && reference > 0
                        && input[reference + 0] == input[iidx + 0]
                        && input[reference + 1] == input[iidx + 1]
                        && input[reference + 2] == input[iidx + 2]
                        )
                    {
                        /* match found at *reference++ */
                        uint len = 2;
                        uint maxlen = (uint)inputLength - iidx - len;
                        maxlen = maxlen > MaxRef ? MaxRef : maxlen;

                        if (oidx + lit + 1 + 3 >= outputLength)
                        {
                            return 0;
                        }

                        do
                        {
                            len++;
                        }
                        while (len < maxlen && input[reference + len] == input[iidx + len]);

                        if (lit != 0)
                        {
                            output[oidx++] = (byte)(lit - 1);
                            lit = -lit;
                            do
                            {
                                output[oidx++] = input[iidx + lit];
                            }
                            while ((++lit) != 0);
                        }

                        len -= 2;
                        iidx++;

                        if (len < 7)
                        {
                            output[oidx++] = (byte)((off >> 8) + (len << 5));
                        }
                        else
                        {
                            output[oidx++] = (byte)((off >> 8) + (7 << 5));
                            output[oidx++] = (byte)(len - 7);
                        }

                        output[oidx++] = (byte)off;

                        iidx += len - 1;
                        hval = (uint)(((input[iidx]) << 8) | input[iidx + 1]);

                        hval = (hval << 8) | input[iidx + 2];
                        _hashTable[((hval ^ (hval << 5)) >> (int)(((3 * 8 - Hlog)) - hval * 5) & (Hsize - 1))] = iidx;
                        iidx++;

                        hval = (hval << 8) | input[iidx + 2];
                        _hashTable[((hval ^ (hval << 5)) >> (int)(((3 * 8 - Hlog)) - hval * 5) & (Hsize - 1))] = iidx;
                        iidx++;
                        continue;
                    }
                }
                else if (iidx == inputLength)
                {
                    break;
                }

                /* ���Ǳ����ٸ���һ���ı��ֽ� */
                lit++;
                iidx++;

                if (lit == MaxLit)
                {
                    if (oidx + 1 + MaxLit >= outputLength)
                    {
                        return 0;
                    }

                    output[oidx++] = (byte)(MaxLit - 1);
                    lit = -lit;
                    do
                    {
                        output[oidx++] = input[iidx + lit];
                    }
                    while ((++lit) != 0);
                }
            }

            if (lit != 0)
            {
                if (oidx + lit + 1 >= outputLength)
                {
                    return 0;
                }

                output[oidx++] = (byte)(lit - 1);
                lit = -lit;
                do
                {
                    output[oidx++] = input[iidx + lit];
                }
                while ((++lit) != 0);
            }

            return (int)oidx;
        }


        /// <summary>
        /// Decompresses the data using LibLZF algorithm
        /// </summary>
        /// <param name="input">Reference to the data to decompress</param>
        /// <param name="output">Reference to a buffer which will contain the decompressed data</param>
        /// <returns>Returns decompressed size</returns>
        static int lzf_decompress(byte[] input, ref byte[] output)
        {
            if (input == null || output == null)
            {
                return 0;
            }

            int inputLength = input.Length;
            int outputLength = output.Length;

            // corner case handling
            if (inputLength <= 1)
            {
                if (outputLength >= inputLength)
                {
                    for (int i = 0; i < inputLength; ++i)
                    {
                        output[i] = input[i];
                    }

                    return inputLength;
                }

                return 0;
            }

            uint iidx = 0;
            uint oidx = 0;

            do
            {
                uint ctrl = input[iidx++];

                if (ctrl < (1 << 5)) /* literal run */
                {
                    ctrl++;

                    if (oidx + ctrl > outputLength)
                    {
                        //SET_ERRNO (E2BIG);
                        return 0;
                    }

                    do
                    {
                        output[oidx++] = input[iidx++];
                    }
                    while ((--ctrl) != 0);
                }
                else /* back reference */
                {
                    uint len = ctrl >> 5;

                    int reference = (int)(oidx - ((ctrl & 0x1f) << 8) - 1);

                    if (len == 7)
                    {
                        len += input[iidx++];
                    }

                    reference -= input[iidx++];

                    if (oidx + len + 2 > outputLength)
                    {
                        //SET_ERRNO (E2BIG);
                        return 0;
                    }

                    if (reference < 0)
                    {
                        //SET_ERRNO (EINVAL);
                        return 0;
                    }

                    output[oidx++] = output[reference++];
                    output[oidx++] = output[reference++];

                    do
                    {
                        output[oidx++] = output[reference++];
                    }
                    while ((--len) != 0);
                }
            }
            while (iidx < inputLength);

            return (int)oidx;
        }
    }
}